package com.example.iot.websocket;

import com.example.iot.service.websocket.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.adapter.NativeWebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import javax.websocket.Session;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author ChenXiangpeng
 */
@Service
@Slf4j
public class DefaultWebSocketHandler extends TextWebSocketHandler implements WebSocketMsgEndpoint {
    /**
     * sessionId -> websocketSession集合
     */
    public static final ConcurrentMap<String, WebSocketSession> WEBSOCKET_SESSION_MAP = new ConcurrentHashMap<>();

    @Autowired
    private WebSocketService webSocketService;

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        super.handleTextMessage(session, message);
        webSocketService.handleWebSocketMsg(session, message.getPayload());
    }

    /**
     * websocket建立连接后的操作
     * @param session websocketSession
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        super.afterConnectionEstablished(session);
        String id = session.getId();
        WEBSOCKET_SESSION_MAP.put(id, session);
        log.info("websocket [{}] 连接成功", session.getId());
        // todo 注册处理逻辑
    }

    /**
     * websocket关闭连接后的操作
     * @param session websocketSession
     * @param status 关闭状态
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        super.afterConnectionClosed(session, status);
        WebSocketSession remove = WEBSOCKET_SESSION_MAP.remove(session.getId());
        // 关闭处理逻辑
        webSocketService.handleWebSocketSessionEvent(session, SessionEvent.CLOSED);
        remove.close();
        log.info("websocket [{}] 已关闭连接", session.getId());
    }

    @Override
    public void send(String sessionId, String message) {
        WebSocketSession session = WEBSOCKET_SESSION_MAP.get(sessionId);
        if (Objects.nonNull(session)){
            try{
                Session nativeSession = ((NativeWebSocketSession) session).getNativeSession(Session.class);
                nativeSession.getAsyncRemote().sendText(message);
            }catch (Exception e){
                log.error("websocket [{}] 发送失败", sessionId);
                e.printStackTrace();
            }
        }else{
            log.error("websocket [{}] 连接不存在, 可能已关闭", sessionId);
        }
    }
}
